package com.element.sentinel.exception;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.common.core.exception.code.LimitErrorCode;
import com.common.core.results.VoidResult;
import com.element.sentinel.utils.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @auther wujun.zhang
 * @date 2023-03-10
 * @desc sentinel 异常处理
 */
@Configuration
public class SentinelExceptionHandler implements BlockExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void handle(HttpServletRequest httpServletRequest,
                       HttpServletResponse httpServletResponse,
                       BlockException e) throws Exception {
        logger.error("应用服务限流:", e);
        httpServletResponse.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
        ResponseUtil.writeJson(httpServletResponse, VoidResult.failed(LimitErrorCode.A_API_LIMIT_ERROR));
    }
}